<template>
  <div class="main">
    <div class="header">
      <div class="search flex">

        <span>名称：<el-input style="width: 200px;" size='small' placeholder="请输入盘点单名" v-model="params.name">
        </el-input></span>
        <span style="margin-left: 10px">仓库：<el-select style="width: 200px" v-model="params.warehouseId" size='small'
                                                      placeholder="请选择仓库">
          <el-option v-for="item in warehouseList" :key="item.value" :label="item.warehouseName"
                     :value="item.warehouseId">
          </el-option>
        </el-select></span>
        <span style="margin-left: 10px">日期：<el-date-picker v-model="params.time" size='small' type="daterange"
                                                           range-separator="至"
                                                           start-placeholder="开始日期"
                                                           end-placeholder="结束日期" @change="chooseTime">
        </el-date-picker></span>
        <el-button @click="searchGetCheckList"
                   type="primary"
                   size='small'
                   icon="el-icon-search"
                   style='color:white;margin-left:20px'>查询
        </el-button>
        <el-button
            size="small"
            style="
                margin-left: 10px;
                background-color: #303e9d;
                color: #eeeeee;
              "
            @click="_reset"
            icon="el-icon-refresh"
        >重置
        </el-button>
      </div>
      <div style="margin-bottom: 10px">
        <el-button size='small' style='color:white' @click="addCheck"><i class="el-icon-plus"
                                                                         style="margin-right: 5px"></i>新 增
        </el-button>
      </div>
    </div>
    <div class="mainTable">
      <el-table :height="maxHeight + 'px'" element-loading-text="拼命加载中" element-loading-spinner="el-icon-loading"
                v-loading="loading" border style="width: 100%;font-size: 12px;"
                :data="checkList.list"
                :header-cell-style="{  'fontSize': '14px', 'background-color': '#F3F6FD', 'color': '#333333', 'textAlign': 'center' }"
                :cell-style="{ 'textAlign': 'center' }">
        <el-table-column type="index" width="50" label="序号"></el-table-column>
        <el-table-column prop="checkId" label="盘点单号" min-width="140px"></el-table-column>
        <el-table-column prop="checkName" label="盘点单名" min-width="140px"></el-table-column>
        <el-table-column prop="warehouse.warehouseName" min-width="80px" label="仓库"></el-table-column>
        <el-table-column label="盘点明细" width="600px">
          <template slot-scope="props">
            <el-table :data="props.row.checkDetailList" border
                      maxHeight="300px"
                      :headerCellStyle="{ 'textAlign': 'center', 'fontWeight': '400', }"
                      :cellStyle="{ 'textAlign': 'center' ,'font-size':'12px'}">
              >
              <el-table-column prop="materialId" min-width="100" label="材料编码"></el-table-column>
              <el-table-column prop="productName" min-width="150" label="材料名称"></el-table-column>
              <el-table-column prop="price" min-width="80" label="成本价"></el-table-column>
              <el-table-column min-width="80" label="数量">
                <template slot-scope="props">
                  <el-link :type="props.row.count < 0 ? 'danger' : 'success'">{{
                      props.row.count
                    }}
                  </el-link>
                </template>
              </el-table-column>
              <el-table-column prop="totalPrice" width="100" label="差价"></el-table-column>
            </el-table>
          </template>
        </el-table-column>
        <el-table-column prop="sumXPrice" label="差价总计" width="100"></el-table-column>
        <el-table-column label="状态" width="100">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.checkStatus == 0" type="danger" size="mini">待处理</el-tag>
            <el-tag size="mini" v-if="scope.row.checkStatus == 1" type="success">已通过</el-tag>
            <el-tag size="mini" v-if="scope.row.checkStatus == 2" type="info">已驳回</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="reason" label="原因" width="200"></el-table-column>
        <el-table-column prop="remark" label="备注" width="200"></el-table-column>
        <el-table-column prop="voucher" label="凭证" min-width="80px">
          <template slot-scope="scope">
            <el-image v-for='(v, i) in scope.row.checkVouchersList' :key="i" style="width: 50px; height: 50px"
                      ref="preview" :src="v" :preview-src-list="scope.row.checkVouchersList">
            </el-image>
          </template>
        </el-table-column>
        <el-table-column prop="checkTime" label="盘点日期" width="120"></el-table-column>
        <el-table-column fixed="right" label="操作" width="100">
          <template slot-scope="data">
            <!-- <div>
              <el-link style="color:#ff6a00" @click="changeProcureInfo(data.row)">变更明细</el-link>
            </div> -->
            <div>
              <el-link style="color: #303e9d" @click="updateStatus(true, data.row)" v-if="authorityList.includes(801)">
                通过
              </el-link>
              <el-link style="margin-left: 5px;color: #303e9d" @click="updateStatus(false, data.row)"
                       v-if="authorityList.includes(802)">驳回
              </el-link>
            </div>
            <div>
              <el-link
                  type="primary" style="margin-right: 10px;color: #303e9d"
                  @click="opVouchers(data.row)" v-if="authorityList.includes(803)">修改凭证
              </el-link>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination style='margin-top:20px' align="center" @size-change="handleCheckSizeChange"
                     @current-change="handleCheckCurrentChange" :current-page="checkList.currentPage"
                     :page-sizes="[10,20,30,40,50]" layout="total, sizes, prev, pager, next, jumper"
                     :total="pageCount">
      </el-pagination>
    </div>
    <!-- 新增 -->
    <el-dialog title="新增盘点单" :visible.sync="dialogVisible" width="70%" :before-close="handleClose">
      <div style="" class="createInfo">
        <div>
          <div>名称</div>
          <el-input placeholder="请输入盘点单名" v-model="createdInfo.name" clearable>

          </el-input>
        </div>
        <div>
          <div>
            仓库
          </div>
          <el-select v-model="createdInfo.warehouseId" clearable style='width: 100%;' placeholder="请选择仓库">
            <el-option v-for="item in warehouseList" :key="item.value" :label="item.warehouseName"
                       :value="item.warehouseId">
            </el-option>
          </el-select>
        </div>
        <div>
          <div>盘点日期</div>
          <el-date-picker style="width: 100%;" v-model="createdInfo.time" type="date" placeholder="选择日期">
          </el-date-picker>
        </div>
        <div>
          <div>原因
          </div>
          <el-input placeholder="请输入盘点原因" v-model="createdInfo.reason" clearable>

          </el-input>
        </div>
        <div>
          <div>备注</div>
          <el-input placeholder="请输入备注" rows='8' type="textarea" v-model="createdInfo.remark">

          </el-input>
        </div>
        <div>
          <div>凭证</div>
          <div>
            <rayUpload @url="getImageUrl" v-if="dialogVisible"></rayUpload>
          </div>
        </div>
      </div>
      <div style="margin-top: 20px;">
        <div style='margin-bottom: 10px'><span style="color:red;">*</span>请选择先选择盘点仓库</div>
        <el-table element-loading-text="拼命加载中" element-loading-spinner="el-icon-loading"
                  v-loading="loading" :data="materialList" height="calc(100vh - 250px)"
                  border stripe :cell-style="{ 'textAlign': 'center' }"
                  :header-cell-style="{ 'background-color': '#303e9d', 'color': 'white', 'textAlign': 'center' }">

          <el-table-column type="index" width="50" label="序号"></el-table-column>
          <el-table-column prop="materialId" label="材料编码" min-width="120"></el-table-column>
          <el-table-column prop="material.productName" label="材料名称" min-width="280"></el-table-column>
          <el-table-column prop="material.norm" label="规格" min-width="120"></el-table-column>
          <el-table-column prop="material.color" label="颜色" min-width="100"></el-table-column>
          <el-table-column prop="material.unit" label="单位" min-width="100"></el-table-column>
          <el-table-column prop="material.price" label="成本价" min-width="100"></el-table-column>
          <el-table-column prop="material.salePrice" label="销售价" min-width="100"></el-table-column>
          <el-table-column label="数量" min-width="200">
            <template slot-scope="scope">
              <el-input-number size='mini' v-model.trim="scope.row.count"></el-input-number>
            </template>
          </el-table-column>

        </el-table>
      </div>
      <span slot="footer" class="dialog-footer">
                <el-button @click="handleClose" style="background:#f5f7fa;color: #909399">取 消</el-button>
                <el-button type="primary" @click="addCheckConfirm">确 定</el-button>
            </span>
    </el-dialog>
    <changeBox @close="changeBoxClose" apiName="changeSelectChangeDetailList" v-if="changeBoxStatus"
               :targetId="targetId">
    </changeBox>
    <el-dialog
        :visible.sync="editVouchers"
        :before-close="handleClose"
        width="30%"
        center
    >
      <div style="display: flex;align-items: center;margin-bottom: 50px">
        修改凭证
        <div>
          <span style="color:gray;font-size: 12px;">(粘贴复制即可上传图片)</span>
          <div class="div" style="display: flex;align-items: center">
            <div v-for='(v, i) in editImg' style="display: flex;align-items: center;margin-right: 10px;" :key="i">
              <el-image :key="i" style="width: 50px; height: 50px"
                        ref="preview" :src="host+v" :preview-src-list="editImgList">
              </el-image>
              <div @click="deleteImg(i)">
                <el-icon name="delete"></el-icon>
              </div>
            </div>
          </div>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editVouchers=false" style="background:#f5f7fa;color: #909399">取 消</el-button>
        <el-button style="background:#303e9d;color: whitesmoke" @click="changeImg">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import dayjs from "dayjs";
import Decimal from "decimal.js";

import tableMixins from "@/mixins/tableMixins.vue";
import rayUpload from '@/RayComponents/rayUpload.vue'
import changeBox from '@/RayComponents/materialChange.vue'
import quinn from "@/utils/quinn";
import axios from 'axios';
import {set} from 'vue';

export default {
  name: "checkList",
  mixins: [tableMixins],
  meta: {title: "盘点列表", icon: "el-icon-edit-outline", authorityList: 800, sort: 8},
  components: {
    rayUpload,
    changeBox
  },
  data() {
    return {
      apiName: "classificationMaterialList",
      targetId: '',
      changeBoxStatus: false,
      checkVouchersList: [],
      editImg: [],
      editImgList: [],
      host: this.$imgHost,
      loading: false,
      warehouseList: [],
      dialogVisible: false,
      editVouchers: false,
      params: {
        name: '',
        startTime: '',
        endTime: '',
        warehouseId: ''
      },
      pageCount: 0,
      previewImg: [],
      createdInfo: {
        time: '',
        warehouseId: '',
        name: '',
        remark: '',
        reason: '',
        checkVouchers: ''
      },
      checkList: {
        list: [],
        currentPage: 1,
        pageSize: 10,
        pageNumber: 1
      },
      materialList: [],
      maxHeight: 0,
      authorityList: [],
    };
  },
  mounted() {
    this.$nextTick(() => {
      this.maxHeight = window.innerHeight - 260;
    })
    window.onresize = () => {
      this.$nextTick(() => {
        this.maxHeight = window.innerHeight - 260;
      })
    }
  },
  watch: {
    'createdInfo.warehouseId': {
      handler(newVal, oldVal) {
        if (newVal && newVal !== oldVal) {
          this.getMaterialList();
        }
      },
      deep: true,
      immediate: true
    }
  },
  created() {
    const {authorityList = []} = quinn.getStorage("userDatav3") || store.state.userData || {};
    this.authorityList = authorityList
    this.getWarehouseList();
    this.getCheckList();
    document.addEventListener('paste', this.handlePaste)
  },
  methods: {
    _reset() {
      this.params = this.$options.data.call(this).params
    },
    getWarehouseList() {
      this.$api.warehouseWarehousePullDownList({pageNumber: 1, pageSize: 100000}).then(async res => {
        this.warehouseList = res;
      })
    },
    handlePaste(event) {
      if (!this.editVouchers) return;
      const clipboardData = event.clipboardData || window.clipboardData;
      if (clipboardData) {
        for (let i = 0; i < clipboardData.items.length; i++) {
          const item = clipboardData.items[i];

          if (item.kind === 'file' && item.type.startsWith('image/')) {
            const file = item.getAsFile();
            if (file) {
              this.uploadImage(file);
            }
          } else {
            this.$message.error('请拷贝图片!');
            break;
          }
        }
      }
    },
    uploadImage(imageFile) {
      const formData = new FormData();
      formData.append('file', imageFile);
      axios.post(`${this.$apiHost}/img/fileImgUrl`, formData, {
        headers: {
          'Content-Type': 'multipart/form-data',
          'token': window.$quinn.getStorage("tokenv3")
        }
      })
          .then(response => {
            this.editImg.push(response.data.result[0]);
            this.editImgList.push(this.host + response.data.result[0]);
          })
          .catch(error => {
          });
    },
    changeBoxClose(e) {
      this.changeBoxStatus = e;
    },
    changeProcureInfo(info) {
      this.targetId = info.checkId;
      this.changeBoxStatus = true;
    },
    chooseTime(e) {
      this.params.startTime = dayjs(e[0]).format("YYYY-MM-DD");
      this.params.endTime = dayjs(e[1]).format("YYYY-MM-DD");
    },
    getCheckList() {
      this.$api.checkCheckList({
        pageSize: this.checkList.pageSize,
        pageNumber: this.checkList.pageNumber,
        checkName: this.params.name,
        startTime: this.params.startTime,
        endTime: this.params.endTime,
        warehouseId: this.params.warehouseId
      }).then(res => {
        this.loading = false;
        this.pageCount = res.count
        this.checkList.count = res.count;
        res.rows.map(el => {
          el.checkDetailList.map(k => {
            k.totalPrice = Decimal(k.price).mul(Decimal(k.count)).toNumber();
          })
          if (el.checkVouchers) {
            el.checkVouchers = el.checkVouchers.split(',');
            el.checkVouchersList = [];
            el.checkVouchers.map(k => {
              el.checkVouchersList.push(this.$imgHost + k);
            })

          } else {
            el.checkVouchersList = []
            el.checkVouchers = []
          }
        })
        this.checkList.list = res.rows;
      })

    },
    getImageUrl(e) {
      this.createdInfo.checkVouchers = e;
    },
    getMaterialList() {
      this.$api.inventoryInventoryList({
        pageSize: 100000,
        pageNumber: 1,
        warehouseId: this.createdInfo.warehouseId
      }).then(res => {
        res.rows.map(el => {
          el.count = 0
        })
        this.materialList = res.rows;
      })
    },
    searchGetCheckList() {
      this.checkList.pageNumber = 1;
      this.getCheckList();
    },
    addCheck() {
      this.dialogVisible = true;
    },
    handleCheckSizeChange(e) {
      this.checkList.pageSize = e;
      this.getCheckList();
    },
    handleCheckCurrentChange(e) {
      this.checkList.pageNumber = e;
      this.getCheckList();
    },
    handleClose() {
      console.log('LLL')
      this.dialogVisible = false;
      this.editVouchers = false;
      this.createdInfo.time = '';
      this.createdInfo.reason = '';
      this.createdInfo.remark = '';
      this.createdInfo.name = '';
      this.createdInfo.warehouseId = ''
      this.createdInfo.checkVouchers = ''
      this.materialList = [];
    },
    updateStatus(type, info) {
      if (info.checkStatus !== 0) {
        this.$message.error('当前盘点单已处理!');
        return;
      }

      this.$alert(`修改ID为:${info.checkId}盘点单状态`, '提示', {
        confirmButtonText: '确定',
        callback: (res) => {
          if (res === 'confirm') {
            this.$api.checkUpdateStatus(
                {
                  type: type,
                  checkId: info.checkId,
                  warehouseId: info.warehouseId
                }
            ).then(res => {
              this.$message({message: "操作成功！", type: "success"})
              this.getCheckList();
            })
          }
        }
      });
    },
    addCheckConfirm() {
      let list = [];
      this.materialList.map(el => {
        if (el.count !== 0 && el.count !== '') {
          el.productName = el.material.productName;
          el.price = el.material.price;
          el.salePrice = el.material.salePrice;
          list = list.concat(el)
        }
      })
      if (list.length == 0) {
        this.$message.error('请添加盘点材料!');
        return
      }
      for (let i in this.createdInfo) {
        if (this.createdInfo[i] == '') {
          this.$message.error('请输入盘点单信息!');
          return
        }
      }
      this.createdInfo.time = dayjs(this.createdInfo.time).format("YYYY-MM-DD");
      this.$api.checkCheckAdd({
        checkDetailList: list,
        checkTime: this.createdInfo.time,
        reason: this.createdInfo.reason,
        remark: this.createdInfo.remark,
        checkName: this.createdInfo.name,
        warehouseId: this.createdInfo.warehouseId,
        checkVouchers: this.createdInfo.checkVouchers
      }).then(res => {
        this.createdInfo.time = '';
        this.createdInfo.reason = '';
        this.createdInfo.remark = '';
        this.createdInfo.name = '';
        this.createdInfo.warehouseId = ''
        this.createdInfo.checkVouchers = ''
        this.materialList = [];
        this.$message({message: "操作成功！", type: "success"})
        this.getCheckList();
        this.dialogVisible = false;
      })
    },
    opVouchers(row) {
      // console.log(row)
      this.editVouchers = true
      this.editImgId = row.checkId
      this.editImg = row.checkVouchers
      this.editImgList = row.checkVouchersList
    },
    deleteImg(i) {
      this.editImg.splice(i, 1)
    },
    changeImg() {
      const data = {
        checkVouchers: this.editImg.toString(),
        checkId: this.editImgId
      }
      this.$api.checkUpdateCheckInventoryVouchers(data).then(res => {
        this.$message({message: "操作成功！", type: "success"})
        this.editVouchers = false
        this.getCheckList()
      })
    }
  },
};
</script>

<style lang="less" scoped>
@import "../../assets/css/public.css";
</style>
